package com.javase.algorithm.leetcode;

/**
 * @author liyanhao
 * @Date 2022-09-22 10:40
 */
public class LC04 {
    public static void main(String[] args) {
        LC04 lc04 = new LC04();
        int[] nums1 = new int[]{1,1,1,1,1,1,1,1,1,1,4,4};
        int[] nums2 = new int[]{1,3,4,4,4,4,4,4,4,4,4};
        double medianSortedArrays = lc04.findMedianSortedArrays(nums1, nums2);
        System.out.println(medianSortedArrays);
    }

    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        //找到合并点
        int i = 0, j = 0, k = 0;
        int length = nums1.length;
        int length1 = nums2.length;
        double[] arr = new double[length + length1];

        if ((nums1 == null || nums1.length == 0) && nums2 != null && nums2.length != 0) {
            for (int l = 0; l < nums2.length; l++) {
                arr[k] = nums2[l];
                k++;
            }
        } else if ((nums2 == null || nums2.length == 0) && nums1 != null && nums1.length != 0) {
            for (int l = 0; l < nums1.length; l++) {
                arr[k] = nums1[l];
                k++;
            }
        } else {
            while (i < length && j < length1) {
                if (nums1[i] < nums2[j]) {
                    arr[k] = nums1[i];
                    i++;
                    k++;
                } else if (nums2[j] < nums1[i]) {
                    arr[k] = nums2[j];
                    j++;
                    k++;
                } else {
                    arr[k] = nums1[i];
                    k++;
                    arr[k] = nums2[j];
                    k++;
                    i++;
                    j++;
                }
                if (j == length1) {
                    while (i < length) {
                        arr[k] = nums1[i];
                        k++;
                        i++;
                    }
                }
                if (i == length) {
                    while (j < length1) {
                        arr[k] = nums2[j];
                        k++;
                        j++;
                    }
                }
            }
        }
        if (k == 0) {
            return 0;
        }
        if (k == 0) {
            return arr[0];
        }
        if (k % 2 == 0) {
            return (arr[k / 2 - 1] + arr[k / 2]) / 2;
        } else {
            return arr[k / 2];
        }
    }

}
